<template>
	<view class="page">
		<page-wraper>
			<view style="text-align: center;" v-if="orderInfo.wait_for_pay_amount == 0 && orderInfo.create_label_status == 0">
				<wd-loading size="50px" />
				
				<view style="margin-top: 20rpx;">
					{{ message }}
				</view>
			</view>
			
			<view class="content" v-if="orderInfo">
				<!-- 取件提醒 -->
				<view class="tips-card"
					v-if="orderInfo.wait_for_pay_amount == 0 && orderInfo.collect_type == 1 && orderInfo.create_label_status > 0 && orderInfo.route_status == '待揽收'">
					<view class="title">取件提醒</view>
					<view class="text">您的运单标签和发票已制作完成，请下载后各打印1份，并致电美国800-7827892加拿大506-8774877预约上门取件时间，或咨询附近收件站点位置并自行送达。
					</view>
				</view>

				<view class="info-card" v-if="orderInfo.wait_for_pay_amount == 0 && orderInfo.order_status == 2 && orderInfo.create_label_status > 0">
					<wd-grid fixed bordered safeAreaInsetBottom placeholder :clickable="true">
						<wd-grid-item icon="download1" text="下载Label" @itemclick="downloadLabel" />
						<wd-grid-item icon="download1" text="下载发票" @itemclick="downloadInvoice" />
					</wd-grid>
				</view>

				<!-- 订单信息 -->
				<view class="info-card">
					<view class="card-title">订单信息</view>
					<view class="info-item">
						<text class="label">订单号：</text>
						<text class="value">{{ orderInfo.po_number }}</text>
					</view>
					<view class="info-item">
						<text class="label">状态：</text>
						<text class="value">{{ statusMap[orderInfo.order_status] }}</text>
					</view>
					<view class="info-item">
						<text class="label">下单时间</text>
						<text class="value">{{ orderInfo.created }}</text>
					</view>
					<view class="info-item">
						<text class="label">费用</text>
						<text class="value primary">{{ orderInfo.charge }} {{ orderInfo.currency }}</text>
					</view>
					<view class="info-item" v-if="orderInfo.wait_for_pay_amount > 0">
						<text class="label">待支付费用</text>
						<text class="value primary">{{ orderInfo.wait_for_pay_amount }} {{ orderInfo.currency }}</text>
					</view>
					<view class="info-item" v-if="orderInfo.paid_time">
						<text class="label">支付时间</text>
						<text class="value">{{ orderInfo.paid_time || '-' }}</text>
					</view>
				</view>
			</view>

			<!-- 收件人信息 -->
			<view class="info-card">
				<view class="card-title">寄件人信息</view>
				<view class="info-item">
					<text class="label">姓名</text>
					<text class="value">{{ orderInfo.shipper_address?.name }}</text>
				</view>
				<view class="info-item">
					<text class="label">电话</text>
					<text class="value">{{ orderInfo.shipper_address?.phone_number }}</text>
				</view>
				<view class="info-item">
					<text class="label">邮箱</text>
					<text class="value">{{ orderInfo.shipper_address?.email || '-' }}</text>
				</view>
				<view class="info-item">
					<text class="label">地址</text>
					<text class="value" v-if="orderInfo.shipper_address">
						<template v-if="orderInfo.shipper_address.country_code === 'CN'">
							{{ orderInfo.shipper_address.state_code }} {{ orderInfo.shipper_address.city }} {{
								orderInfo.shipper_address.address1 }} {{ orderInfo.shipper_address.address2 }}
						</template>
						<template v-else>
							{{ orderInfo.shipper_address.address1 }}
							<div v-if="orderInfo.shipper_address.address2">
								{{ orderInfo.shipper_address.address2 }}
							</div>
							<div>
								{{ orderInfo.shipper_address.city }}, {{ orderInfo.shipper_address.state_code }}, {{
									orderInfo.shipper_address.postal_code }} ({{ orderInfo.shipper_address.country_code }})
							</div>
						</template>
					</text>
				</view>
				<view class="info-item">
					<text class="label">取件方式</text>
					<text class="value">{{ collectTypeMap[orderInfo.collect_type] }}</text>
				</view>
				<view class="info-item" v-if="orderInfo.collect_type === 1">
					<text class="label">取件时间</text>
					<text class="value">{{ orderInfo.ship_date.substring(0, 10) }} {{ timeRanges[orderInfo.ship_time] }}</text>
				</view>
			</view>

			<!-- 收件人信息 -->
			<view class="info-card">
				<view class="card-title">收件人信息</view>
				<view class="info-item">
					<text class="label">姓名</text>
					<text class="value">{{ orderInfo.address.name }}</text>
				</view>
				<view class="info-item">
					<text class="label">电话</text>
					<text class="value">{{ orderInfo.address.phone_number }}</text>
				</view>
				<view class="info-item">
					<text class="label">邮箱</text>
					<text class="value">{{ orderInfo.address.email || '-' }}</text>
				</view>
				<view class="info-item">
					<text class="label">地址</text>
					<text class="value" v-if="orderInfo.address">
						<template v-if="orderInfo.address.country_code === 'CN'">
							{{ orderInfo.address.state_code }} {{ orderInfo.address.city }} {{
								orderInfo.address.address1 }} {{ orderInfo.address.address2 }}
						</template>
						<template v-else>
							{{ orderInfo.address.address1 }}
							<div v-if="orderInfo.address.address2">
								{{ orderInfo.address.address2 }}
							</div>
							<div>
								{{ orderInfo.address.city }}, {{ orderInfo.address.state_code }}, {{
									orderInfo.address.postal_code }} ({{ orderInfo.address.country_code }})
							</div>
						</template>
					</text>
				</view>
			</view>

			<!-- 物品信息 -->
			<view class="info-card">
				<view class="card-title">包裹信息</view>
				<view class="item-list">
					<view class="item" v-for="(item, index) in orderInfo.packages" :key="index">
						<view class="item-header">
							<text class="name">包裹{{ index + 1 }}</text>
							<text class="count">{{ item.length }}×{{ item.width }}×{{ item.height }} {{ item.dims_unit }} - {{
								item.weight }}
								{{ item.weight_unit }}</text>
						</view>
						<view class="item-footer" @click="() => showRoutesDetail(item.id)">
							<wd-steps :active="1" vertical>
								<wd-step :title="item.route_status" v-if="item.route_title">
									<template #description>
										{{ item.route_title }}
										<div>{{ item.route_time }}</div>
									</template>
								</wd-step>
							</wd-steps>
						</view>
					</view>
				</view>
			</view>

			<!-- 物品信息 -->
			<view class="info-card">
				<view class="card-title">清关信息</view>
				<view class="item-list">
					<view class="item" v-for="(item, index) in orderInfo.items" :key="index">
						<view class="item-header">
							<text class="name">{{ item.description }}</text>
							<text class="count">{{ item.pieces }}件</text>
						</view>
						<view class="item-info">
							<text>总重量：{{ item.weight * item.pieces }} {{ item.weight_unit }}</text>
							<text>总申报价值：{{ item.declared_value * item.pieces }} {{ item.declared_value_currency }}</text>
						</view>
					</view>
				</view>
			</view>

			<wd-popup v-model="showRoutes" position="bottom" custom-style="height: 300px; padding: 20rpx;">
				<wd-steps :active="0" vertical>
					<wd-step v-for="(item, index) in routesDetail" :key="index"
						:title="`${item.route_status || ''} - ${item.location}`">
						<template #description>
							{{ item.route_title }}
							<div>{{ item.route_time }}</div>
						</template>
					</wd-step>
				</wd-steps>
			</wd-popup>
		</page-wraper>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted } from 'vue'

	const message = ref('请稍后...');
	const orderInfo = ref<any>({
		shipper_address: {},
		address: {}
	})
	const statusMap = ref<any>({
		0: "已取消",
		1: "待支付",
		2: "支付成功"
	})
	const collectTypeMap = ref<any>({
		1: "预约免费上门取件",
		2: "自行到门店投递"
	})
	const timeRanges = ref<any>({
		1: '上午 09:00-12:00',
		2: '下午 14:00-18:00'
	});
	const showRoutes = ref<boolean>(false);
	const routesDetail = ref<any>([]);

	onMounted(() => {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		// @ts-ignore
		const orderId = currentPage.options.id
		if (orderId) {
			loadOrderDetail(orderId)
		}
	})

	const showRoutesDetail = async (packageId : string) => {
		uni.showLoading({
			title: '加载中'
		});

		try {
			const res = await uni.$http.get(`/main/routes/${packageId}`);

			uni.hideLoading();

			if (res.data.code == 0) {
				showRoutes.value = true;
				routesDetail.value = res.data.data;
			}
		} catch (error) {
			uni.hideLoading();
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		}
	}

	const loadOrderDetail = async (orderId : string) => {
		try {
			const res = await uni.$http.get(`/user/order/get_order_info/${orderId}`);

			if (res.data.code == 0) {
				orderInfo.value = res.data.data;
				
				if(orderInfo.value.wait_for_pay_amount == 0 && orderInfo.value.create_label_status == 0) {
					message.value = `您的运单<${orderInfo.value.po_number}>已提交，标签和发票系统制作中，请耐心等待！`;
					
					const timer = setInterval(async () => {
					    uni.$http.get(`/user/order/check/${orderInfo.value.po_number}`).then(res => {
					        if (res.data.code == 0) {
					            clearTimeout(timer);
								
								orderInfo.value.create_label_status = 1;
					        }
					    });
					}, 1000);
				}
			}
		} catch (error) {
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		}
	}

	function base64ToBlob(text, content_type) {
		var byteString = atob(text);
		var arrayBuffer = new ArrayBuffer(byteString.length);
		var intArray = new Uint8Array(arrayBuffer);

		for (var i = 0; i < byteString.length; i++) {
			intArray[i] = byteString.charCodeAt(i);
		}

		return new Blob([intArray], {
			type: content_type
		});
	}

	function downloadLabel() {
		console.log('downloadLabel');
		/*#ifdef MP-WEIXIN*/
		uni.showLoading({ title: '请稍后...' })

		uni.$downloadFile({
			url: `user/order/label2/${orderInfo.value.id}`,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.openDocument({
						filePath: res.tempFilePath,
						showMenu: true, // 开启时右上角会有三点，点击可以保存
						success: (res) => {
							console.log('打开文档成功')
						},
						fail: (res) => {
							uni.showToast({ title: '打开文件失败', icon: 'error' })
						},
						complete: () => {
							uni.hideLoading()
						},
					})
				} else {
					uni.showToast({ title: '获取文件失败', icon: 'error' })
				}
			},
			fail: (res) => {
				uni.showToast({ title: '获取文件失败', icon: 'error' })
			},
			complete: () => {
				uni.hideLoading()
			},
		});
		/*#endif*/

		/*#ifdef H5*/
		uni.$http.post(`user/order/label`, { ids: [orderInfo.value.id] }).then(res => {
			if (res.data.code === 0) {
				const blob = base64ToBlob(
					res.data.data,
					res.data.msg == ".zip"
						? "application/x-zip-compressed"
						: "application/pdf"
				);

				let dymaicName = orderInfo.po_number;
				let fileName = `${dymaicName}${res.data.msg == ".zip" ? ".zip" : ".pdf"}`;

				const el = document.createElement("a");

				el.download = fileName;
				el.style.display = "none";
				el.href = URL.createObjectURL(blob);
				document.body.appendChild(el);

				el.click();

				URL.revokeObjectURL(el.href);
				document.body.removeChild(el);
			} else {
				uni.showToast({
					title: res.data.msg,
					icon: 'error'
				});
			}
		}).catch(e => {
			uni.showToast({
				title: e.message,
				icon: 'error'
			});
		});
		/*#endif*/
	}

	function downloadInvoice() {
		/*#ifdef MP-WEIXIN*/
		uni.showLoading({ title: '请稍后...' })

		uni.$downloadFile({
			url: `user/order/invoice2/${orderInfo.value.id}`,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.openDocument({
						filePath: res.tempFilePath,
						showMenu: true, // 开启时右上角会有三点，点击可以保存
						success: (res) => {
							console.log('打开文档成功')
						},
						fail: (res) => {
							uni.showToast({ title: '打开文件失败', icon: 'error' })
						},
						complete: () => {
							uni.hideLoading()
						},
					})
				} else {
					uni.showToast({ title: '获取文件失败', icon: 'error' })
				}
			},
			fail: (res) => {
				uni.showToast({ title: '获取文件失败', icon: 'error' })
			},
			complete: () => {
				uni.hideLoading()
			},
		});
		/*#endif*/

		/*#ifdef H5*/
		uni.$http.get(`user/order/invoice/${orderInfo.value.id}`).then(res => {
			if (res.data.code === 0) {
				const blob = base64ToBlob(
					res.data.data,
					"application/vnd.ms-excel"
				);

				let dymaicName = orderInfo.po_number;
				let fileName = `${dymaicName}.xls`;

				const el = document.createElement("a");

				el.download = fileName;
				el.style.display = "none";
				el.href = URL.createObjectURL(blob);
				document.body.appendChild(el);

				el.click();

				URL.revokeObjectURL(el.href);
				document.body.removeChild(el);
			} else {
				uni.showToast({
					title: res.data.msg,
					icon: 'error'
				});
			}
		}).catch(e => {
			uni.showToast({
				title: e.message,
				icon: 'error'
			});
		});
		/*#endif*/
	}
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background-color: #f6f6f6;
	}

	.content {
		margin-top: 24rpx;
		margin-left: 5rpx;
		margin-right: 5rpx;
	}

	.status-card {
		background-color: #007AFF;
		color: #fff;
		padding: 32rpx 24rpx;
		border-radius: 12rpx;
		margin-bottom: 24rpx;

		.status {
			font-weight: 500;
			margin-bottom: 16rpx;
		}

		.order-no {
			opacity: 0.8;
		}
	}

	.tips-card {
		background-color: orange;
		color: #fff;
		padding: 32rpx 24rpx;
		border-radius: 12rpx;
		margin-bottom: 24rpx;

		.title {
			font-weight: 500;
			margin-bottom: 16rpx;
		}

		.text {
			opacity: 0.8;
		}
	}

	.info-card {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		margin-left: 5rpx;
		margin-right: 5rpx;

		.card-title {
			font-weight: 500;
			margin-bottom: 24rpx;
			color: #333;
		}

		.info-item {
			display: flex;
			justify-content: space-between;
			margin-bottom: 16rpx;

			.label {
				color: #666;
			}

			.value {
				color: #333;

				&.primary {
					color: #007AFF;
					font-weight: 500;
				}
			}
		}
	}

	.item-list {
		.item {
			border-bottom: 1px solid #f5f5f5;
			padding: 16rpx 0;

			&:last-child {
				border-bottom: none;
			}

			.item-header {
				display: flex;
				justify-content: space-between;
				margin-bottom: 12rpx;

				.name {
					color: #333;
				}

				.count {
					color: #666;
				}
			}

			.item-info {
				color: #999;
				display: flex;
				gap: 24rpx;
			}
		}
	}
</style>